from docx import  Document
from docx.shared import  Pt
from docx.oxml.ns import  qn
from docx.shared import Inches, Cm
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import pypinyin

#打开文档
tablecols = 11
pinstr =  '春天寻找姑娘野花眼睛柳枝桃花杏花鲜花邮递员先生原来大叔邮局东西太太做客惊奇快活去年'
pinstr += '美好礼物爷爷植树碧空如洗万里无云公园格外引人注目汗珠休息柏树树苗小心笔直叔叔足迹昨天'
pinstr += '迷路温暖爱心一定也许桌子平时难道味道就是加工种子农具甜菜工具劳动经过出色河水碧绿波纹'
pinstr += '河岸柳叶景色恋恋不舍柳树枝条神州中华山川黄河长江长城台湾岛海峡民族奋发节日春节花灯清明节'
pinstr += '先人龙舟中秋圆月转眼全家团圆热闹动物贝壳甲骨文张开样子可以钱币钱财有关美食红烧茄子烤鸭羊肉'
pinstr += '蛋炒饭彩色脚尖森林雪松歌声苹果精灵季节喜欢好像说话普通说话阿姨对岸弟弟游戏发明字母周围补充'
pinstr += '公主勇士飞机地道火药胜利叫喊忘记屁股苍耳留神干净从来幸运比如使劲亡羊补牢劝告筋疲力尽明白图画'
pinstr += '老师讲桌座位哈哈大笑五角星然后神情发现角度愿意麦子为难身边四周立刻突然吃惊认真脚步难为情'
pinstr += '雷雨乌云闪电雷声房子窗户野外大自然天然指南针帮助向导指点北方北极星路灯永远黑夜帮忙南方特别'
pinstr += '积雪太空生活宇宙飞船别处喝水杯子失去使用半空地板容易浴室方向耳朵扇子遇到兔子后来不安毛病头痛最后只要人家'
pinstr += '飞虫决定商店木屋工夫终于围巾星期青蛙草籽野鸭泉水竹子应该花丛尽情道路毛虫叶子目光周游纺织编织怎样声音花纹消失'
pinstr += '祖先原始意思浓绿一望无边蓝天野谷野兔赛跑回忆世界学习成功月亮主意一直只好反反复复变化方式简单自由生长泥土相当最好结局开头东边光明觉得值日火球沙石人类艰难决心苦海炎热害怕从此东方西方花草树木重新生机'

pinstr = pypinyin.pinyin(pinstr)

document = Document()
document.sections[0].left_margin = Inches(0.7)
document.sections[0].right_margin = Inches(0.7)

#加入标题
run = document.add_paragraph()
run = run.add_run('部编语文二年级下册看拼音词语')
run.font.name=u'宋体'

#增加表格
cn = len(pinstr)
tablerows = cn // tablecols
tablerows *= 2
lastrows = cn % tablecols

if lastrows > 0:
    tablerows += 2
table = document.add_table(rows=tablerows, cols=tablecols)
table.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
c = 1
pc = 1
while c < tablerows - 2:
    pin_cells = table.rows[c-1].cells
    hdr_cells = table.rows[c].cells
    for i in range(0,tablecols):
        pos = (c - pc) * tablecols + i
        pin_cells[i].text = pinstr[pos]
        pin_cells[i].paragraphs[0].paragraph_format.space_before = Pt(0)
        pin_cells[i].paragraphs[0].paragraph_format.space_after  = Pt(0)
        pin_cells[i].paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
        run = hdr_cells[i].paragraphs[0].add_run()
        run.add_picture('tzg.png', width=Cm(1.3), height=Cm(1.3))
        run.font.name=u'宋体'
    c  += 2
    pc += 1


if lastrows > 0:
    pin_cells = table.rows[c-1].cells
    hdr_cells = table.rows[c].cells
    for i in range(0,lastrows):
        pos = (c - pc) * tablecols + i
        pin_cells[i].text = pinstr[pos]
        pin_cells[i].paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
        pin_cells[i].paragraphs[0].paragraph_format.space_before = Pt(0)
        pin_cells[i].paragraphs[0].paragraph_format.space_after  = Pt(0)
        run = hdr_cells[i].paragraphs[0].add_run()
        run.add_picture('tzg.png', width=Cm(1.3), height=Cm(1.3))
        run.font.name=u'宋体'


#保存文件
document.save('demo.docx')

os.startfile('demo.docx')